<template>
  <div style="margin-top: 10px">
    <div class="left-operation-container">
      <t-button @click="addAppInfo"> 新增应用 </t-button>
    </div>
    <t-table
      :data="data"
      :columns="APP_COLUMNS"
      :row-key="rowKey"
      vertical-align="top"
      :hover="true"
      :pagination="pagination"
      :selected-row-keys="selectedRowKeys"
      :loading="dataLoading"
      :header-affixed-top="{ offsetTop, container: getContainer }"
      @page-change="rehandlePageChange"
      @change="rehandleChange"
      @select-change="rehandleSelectChange"
    >
      <template #rate="{ row }">
        <span>{{ row.rate }}%</span>
      </template>
      <template #paymentStatus="{ row }">
        <t-tag v-if="row.paymentStatus === true" theme="success" variant="light">己启用</t-tag>
        <t-tag v-else theme="warning" variant="light">己关闭</t-tag>
      </template>
      <template #payChannel="{ row }">
        <t-tag v-if="row.payChannel === 1">微信支付</t-tag>
        <t-tag v-if="row.payChannel === 2">支付宝</t-tag>
      </template>

      <template #op="slotProps">
        <a class="t-button-link" @click="handleClickDetail(slotProps)">详情</a>

        <a class="t-button-link" @click="handleClickDelete(slotProps)">删除</a>
      </template>
    </t-table>

    <app-edit :visible="detailVisible" :app-id="appId" :on-save="fetchData" @onClose="closeDetail"></app-edit>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';

import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next';
import AppEdit from './components/AppEdit.vue';

import { useSettingStore } from '@/store';
import { prefix } from '@/config/global';

import { APP_COLUMNS } from './constants';
import { getAppList, delApp } from '@/api/settings';

const appId = ref('');
const detailVisible = ref(false);

const openDetail = () => {
  detailVisible.value = true;
};
const closeDetail = () => {
  detailVisible.value = false;
};
const addAppInfo = () => {
  detailVisible.value = true;
  appId.value = '';
};
const delAppInfo = (appId: string) => {
  delApp(appId)
    .then((ret) => {
      MessagePlugin.info('操作成功');
    })
    .catch((e) => {
      MessagePlugin.error(e.message);
    });
};
const store = useSettingStore();

const data = ref([]);
const pagination = ref({
  defaultPageSize: 20,
  total: 100,
  defaultCurrent: 1,
});

const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    data.value = await getAppList();
    pagination.value = {
      ...pagination.value,
      total: data.value.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const deleteIdx = ref(-1);
const confirmBody = computed(() => {
  if (deleteIdx.value > -1) {
    const { name } = data.value[deleteIdx.value];
    return `删除后，所有信息将被清空，且无法恢复`;
  }
  return '';
});

onMounted(() => {
  fetchData();
});

const confirmVisible = ref(false);

const selectedRowKeys = ref([1, 2]);

const router = useRouter();

const resetIdx = () => {
  deleteIdx.value = -1;
};

const onConfirmDelete = () => {
  // 真实业务请发起请求
  data.value.splice(deleteIdx.value, 1);
  pagination.value.total = data.value.length;
  const selectedIdx = selectedRowKeys.value.indexOf(deleteIdx.value);
  if (selectedIdx > -1) {
    selectedRowKeys.value.splice(selectedIdx, 1);
  }
  confirmVisible.value = false;
  MessagePlugin.success('删除成功');
  resetIdx();
};

const onCancel = () => {
  resetIdx();
};

const rowKey = 'index';

const rehandleSelectChange = (val: number[]) => {
  selectedRowKeys.value = val;
};
const rehandlePageChange = (curr, pageInfo) => {
  console.log('分页变化', curr, pageInfo);
};
const rehandleChange = (changeParams, triggerAndData) => {
  console.log('统一Change', changeParams, triggerAndData);
};
const handleClickDetail = (obj: any) => {
  appId.value = obj.row.appId;

  openDetail();
};

const handleClickDelete = (obj: any) => {
  console.log(JSON.stringify(obj));

  const confirmDialog = DialogPlugin.confirm({
    header: '提示',
    body: '删除后该应用将无法发起支付，确定要删除吗？',
    confirmBtn: '确认',
    cancelBtn: '取消',
    onConfirm: ({ e }) => {
      console.log('e: ', e);
      delApp(obj.row.appId)
        .then((ret) => {
          fetchData();
          MessagePlugin.success('操作成功');
        })
        .catch((e) => {
          MessagePlugin.error(e.message);
        });

      // 请求成功后，销毁弹框
      confirmDialog.destroy();
    },
    onClose: ({ e, trigger }) => {
      confirmDialog.hide();
    },
  });
};

const offsetTop = computed(() => {
  return store.isUseTabsRouter ? 48 : 0;
});

const getContainer = () => {
  return document.querySelector(`.${prefix}-layout`);
};
</script>

<style lang="less" scoped>
.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: 8px;
  }
}

.left-operation-container {
  padding: 6px 0;
  margin-bottom: 16px;

  .selected-count {
    display: inline-block;
    margin-left: 8px;
    color: var(--td-text-color-secondary);
  }
}

.search-input {
  width: 360px;
}
</style>
